<template>
  <!-- <h2>预约中心</h2> -->
  <div class="appointment-main" v-loading="loading">
    <div class="appointment-left" v-show="isShowDate">
      <calendarday :isActive="isActive" @getDays="getDay" @getWeeks="getWeeks"></calendarday>
      <div class="opreation">
        <div :class="{'isAvtive': type ==='预约筛选'}" @click="handleClick('预约筛选')" >预约筛选</div>
        <!-- <div :class="{'isAvtive': type ==='待定预约'}" @click="handleClick('待定预约')">待定预约</div> -->
      </div>
      <div class="opreation-plan" v-if="type === '预约筛选'">
        <!-- 预约 -->
        <div  class="make-an-appointment">
          <div class="plan-collapse">
            <div class="plan-head" @click="handShow('预约状态')">
            <span>预约状态</span>
              <div class="icon">
                <span>
                  <el-icon v-if="isShow"><arrow-right /></el-icon>
                  <el-icon v-else><ArrowDown /></el-icon>
                </span>
              </div>
            </div>
            <div class="plan-content ">
              <div v-if="isShow" class="defult-btn">
                <!-- 收起 -->
              </div>
              <div v-else class="show-btn">
                <div class="btn" v-for="item in statusBtnList" :key="item.id">
                  <div class="btn-item" :class="item.name == status ? 'btn-item-active' : ''" @click="onBtnStatus(item.id)">
                    {{item.name}}
                  </div>
                </div>

                
              </div>
            </div>
          </div>
          
        </div>
        <!-- 待定 -->
        <div class="undetermined">
          <div class="plan-collapse">
            <div class="plan-head" @click="handShow('医生筛选')">
            <span>医生筛选</span>
              <div class="icon">
                <span>
                  <el-icon v-if="isUndeterminedShow"><arrow-right /></el-icon>
                  <el-icon v-else><ArrowDown /></el-icon>
                </span>
              </div>
            </div>
            <div class="plan-content content-scroll">
              <div v-if="isUndeterminedShow" class="defult-btn">
                <!-- 收起 -->
              </div>
              <div v-else class="show-btn">
                <div class="btn">
                  
                    <div class="btn-item" :class="doctorID == null ? 'btn-item-active' : ''" @click="searchDoctor(null)">
                    {{'全部'}}
                  </div>
                </div>
                <div class="btn" v-for="doctor in doctorList" :key="doctor.id">
                  <div class="btn-item" :class="doctor.id == doctorID ? 'btn-item-active' : ''" @click="searchDoctor(doctor.id)">
                      {{doctor.name}}
                    </div>
                </div>

              </div>
            </div>
          </div>
        </div>
      </div>
    
    </div>
    <div class="appoinment-right">
        <div class="appoinment-right-head">
          <div class="head-days">
            <template v-if="isActive === 'week'">
              <span>{{startMonth + '月' + startDay + '日'}}</span> - <span >{{endMonth + '月' + endDay + '日'}}</span>
            </template>
            <template v-if="isActive === 'day'">
              <span>{{startMonth + '月' + startDay + '日'}}</span>
            </template>
          </div>
          <div class="days-switch">
            <div class="btns">
              <el-button-group >
                <el-button class="btn-5" :class="{'active' : isActive === 'day'}" @click="handleClickDay('day')">日</el-button>
                <el-button class="btn-5" :class="{'active' : isActive === 'week'}" @click="handleClickDay('week')">周</el-button>
              </el-button-group>
            </div>
            
            <div class="add-btn">
              <el-button  
                class="btn-1" 
                v-jurisdiction="'customer:subscribe:add'" 
                :disabled="isOpenAddAppointment"
                @click="addAppointment"
                >新建预约</el-button>
            </div>
            
          </div>
        </div>
        <scheduling 
          :weekDayList="dayList" 
          :weekDataList="weekDataList" 
          :type="isActive" 
          :firstDate="start"
          :lastDate="end"
          :isMantle="isMantle"
          @reloadList="reloadList"
          @prevWeek="prevWeek"
          @nextWeek="nextWeek"
          @handleOpenEditAnApp="handleOpenEditAnApp"
          @isPutAwayBtn="isPutAwayBtn"
          ></scheduling>
    </div>
    <!-- 预约 -->
    <div class="appoinment-operation" v-if="isOpenAddAppointment">
      <div class="head-title">{{ title || '新建预约'}}</div>
      <zmakeanapp
        @handlebtn="handlebtn"
        @reloadList="reloadList"
        @cancel="cancel"
        :makeanappInfo="makeanappInfo"
      ></zmakeanapp>
    </div>
  </div>

  <!-- 预约 -->
  <!-- <el-drawer
			size="42%"
			:title="title"
			v-model="showDrawer"
			:before-close="drawerClose" destroy-on-close>
    <zaddpatient 
					@cancel="cancel" 
					@saveMakeAnAppointment="saveMakeAnAppointment" 
					@saveAndRegister="saveAndRegister"
					v-if="isADD === 'add'"
		></zaddpatient>
    <zregister v-if="isADD === 'register'"
				@cancel="cancel" 
		></zregister>
    <zmakeanapp
      v-if="isADD === 'makeanapp'"
      @handlebtn="handlebtn"
      @reloadList="reloadList"
      @cancel="cancel"
    ></zmakeanapp>
  </el-drawer> -->

</template>

<script lang="ts">
import { ArrowDown, ArrowRight } from '@element-plus/icons-vue'
import { defineComponent, ref, watch } from "vue";
import { getAllDays } from '../../utils/Date'
import scheduling from '../../components/scheduling/scheduling.vue'
import calendarday from '../../components/calendarday.vue'

import zmakeanapp from "../../components/patient/makeAnAppointment.vue"
import zaddpatient from "../../components/patient/add.vue"
import zregister from "../../components/patient/register.vue"

import { getDoctorListAllAPi } from "../../api/common"
import { getSubscribeByIdApi } from "../../api/reservation"

import useRequet, { RespData } from "../../hook/network"
import { ElMessage, ElMessageBox } from 'element-plus'

interface WeekDay {
  week: string,
  day: string
}
type  Btype = {
  id: string | number,
  name: string,
}

type SeachList = {
  type: string,
  beginTime: string,
  endTime: string,
  selectStatus?: string,
  userId?: number
}

const WEEK_ONE = 1;
const WEEK_TWO = 2;
const WEEK_THREE = 3;
const WEEK_FOUR = 4;
const WEEK_FIVE = 5;
const WEEK_SIX = 6;
const WEEK_SERVER = 0;
export default defineComponent({
  name: 'AppointmentWork',
  components: {
    scheduling,
    calendarday,

    zmakeanapp,
    zaddpatient,
    zregister,

    ArrowDown, ArrowRight
  },
  setup() {
    
    const request = useRequet({ path: "" });

    const type = ref('预约筛选')
    const isShow = ref(false)
    const isUndeterminedShow = ref(false)
    const loading = ref(false)

    const startMonth = ref('')
    const startDay = ref('')
    const endMonth = ref('')
    const endDay = ref('')

    const start = ref('')
    const end = ref('')

    const weekDayList = ref([
      {
        week: '周一',
        day: ''
      },
      {
        week: '周二',
        day: ''
      },
      {
        week: '周三',
        day: ''
      },
      {
        week: '周四',
        day: ''
      },
      {
        week: '周五',
        day: ''
      },
      {
        week: '周六',
        day: ''
      },
      {
        week: '周日',
        day: ''
      }
    ])
    const dayList = ref([] as WeekDay[])
    const weekDataList = ref([] as any[][])
    const isActive = ref('week')
    dayList.value = weekDayList.value
    const handleClick = (status: string) => {
      type.value = status
    }
    const handShow = (type: string) => {
      if(type === '预约状态') {
        isShow.value = !isShow.value
      }
      
      if(type === '医生筛选') {
        isUndeterminedShow.value = !isUndeterminedShow.value
      }
    }

    const doctorList = ref([] as Btype[])
    const statusBtnList = ref([] as Btype[])

    // 点击的 日 周
    const handleClickDay = (type: string) => {
      if(type === 'week') {
        dayList.value = weekDayList.value
        // getAppointmentList()
      }
      isActive.value = type
      
    }

    const getDay = (date: string) => {
      start.value = date
      end.value = ''
      let dates = date.split('-')

      startMonth.value = dates[1]
      startDay.value = dates[2]

      let res = ''
      let weekDay = new Date(date).getDay()
      switch (weekDay) {
        case WEEK_ONE:
          res = '周一'
          break;
        case WEEK_TWO:
          res = '周二'
          break;
        case WEEK_THREE:
          res = '周三'
          break;
        case WEEK_FOUR:
          res = '周四'
          break;
        case WEEK_FIVE:
          res = '周五'
          break;
        case WEEK_SIX:
          res = '周六'
          break;
        case WEEK_SERVER:
          res = '周日'
          break;
        
      }
      dayList.value = [
        {
          week: res,
          day: startMonth.value + '/' + startDay.value
        }
      ]

      getAppointmentList()

    }
    
    const getWeeks = (firstDay: string, lastDay: string) => {
      start.value = firstDay
      end.value = lastDay
      
      let arr = getAllDays(firstDay, lastDay)
        arr.forEach((date: string, i: number) => {
          let month = date.split('-')[1]
          let day = date.split('-')[2]
          weekDayList.value[i].day = month + '/' + day
        })
      
      let firsts = firstDay.split('-')
      let lasts = lastDay.split('-')

      startMonth.value = firsts[1]
      startDay.value = firsts[2]

      endMonth.value = lasts[1]
      endDay.value = lasts[2]

      getAppointmentList()
    }

    const userInfo = window.localStorage.getItem('person')
    const isDoctor = JSON.parse(userInfo!)
    const doctorID = ref()
    const status = ref('全部')
    const isSearchList = ref<null | number>(null)
     // 得到预约列表数据
    const getAppointmentList = () => {
      loading.value = true
      let params: SeachList = {
        type: isActive.value,
        beginTime: start.value,
        endTime: end.value,
      }
      if(doctorID.value) {
        params.userId = doctorID.value
      }
      if(status.value) {
        params.selectStatus = status.value
      }
      request.sendRequest({
        address: 'customer/subscribe/getSubScribeListByDate',
        params,
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
          weekDataList.value = resp.data

          loading.value = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
          
        },
        method: "POST",
      })
    }

    const reloadList = () => {
      getAppointmentList()

      isOpenAddAppointment.value = false

    }

    // 获取医生
    const getDocTorList = async() => {
      let res:any = await getDoctorListAllAPi({});
      if(res.code !== 0) return ElMessage.error(res.msg || '获取信息失败')
      doctorList.value = res.data || [];
      console.log(isDoctor)
      let id = isDoctor.id
      let haveDoctor = doctorList.value.filter(i => i.id == id);
      if(haveDoctor.length > 0) {
        doctorID.value = id;
        getAppointmentList()
      }

      
    }
    getDocTorList()
    // 获取预约状态
    const getSubScribeStatusSelect = () => {
      request.sendRequest({
        address: 'customer/subscribe/getSubScribeStatusSelect',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('获取预约状态' + resp.msg)
          statusBtnList.value = resp.data || []
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('获取预约状态' + resp.msg)
          
        },
        method: "GET",
      }) 
    }
    getSubScribeStatusSelect()

    const onBtnStatus = (val: string | number) => {
      status.value = String(val)
      getAppointmentList()
    }

    // 后面根据医生查询数据
    const searchDoctor = (id: number | string | null) => {
      doctorID.value = id
      if(id) {
        isSearchList.value = Number(id)
      } else {
        isSearchList.value = null
      }
      
      getAppointmentList()
    }

    const setYMD = (time: number) => {
      let date = new Date(time),
          YYYY = date.getFullYear(),
          MM = date.getMonth() + 1,
          dd = date.getDate();
      return `${YYYY}-${MM}-${dd}`
    }

    const prevWeek = () => {
      console.log(start.value, end.value)
      let oneDay = 24 * 60 * 60 * 1000 * 7;
      let starTime = new Date(start.value).getTime() - oneDay;
      let lastTime = new Date(end.value).getTime() - oneDay;
      let startD = setYMD(starTime);
      let lastD = setYMD(lastTime);

      getWeeks(startD, lastD)
    }
    const nextWeek = () => {
      let oneDay = 24 * 60 * 60 * 1000 * 7;
      let starTime = new Date(start.value).getTime() + oneDay;
      let lastTime = new Date(end.value).getTime() + oneDay;
      let startD = setYMD(starTime);
      let lastD = setYMD(lastTime);

      getWeeks(startD, lastD)
    }

    const handleOpenEditAnApp = async(id:number) => {
      await getMakeanapp(id)
      console.log(id)
      title.value = '修改预约'
      isOpenAddAppointment.value = true
      isMantle.value = true
    }

    const makeanappInfo = ref({} as any)
    // 获取预约信息
    const getMakeanapp = async(id: number) => {
      makeanappInfo.value = {}
      
      let resp: any = await getSubscribeByIdApi({}, id)
      console.log(resp)
      makeanappInfo.value = resp.data
    }

    // 左边日期
    const isShowDate = ref(true)
    const isPutAwayBtn = () => {
      isShowDate.value = !isShowDate.value
    }
    // 右侧预约布局
    const isOpenAddAppointment = ref(false)
    const isMantle = ref(false)

    // 新建预约部分
    const showDrawer = ref(false)
    const title = ref('新建预约')
    const isADD = ref('')
    // 打开新建预约
    const addAppointment = () => {
      // isADD.value = 'makeanapp'
      // showDrawer.value = true
      makeanappInfo.value = {}
      title.value = '新建预约'
      isOpenAddAppointment.value = true
      isMantle.value = true
    }
    const saveMakeAnAppointment = () => {
      isADD.value = 'makeanapp'
			title.value = "新建预约"
    }

    const saveAndRegister = () => {
			isADD.value = 'register'
			title.value = "挂号"
		}


    const handlebtn = () => {
      isADD.value = 'add'
			title.value = "个人信息"
    }
    const drawerClose = () => {
      ElMessageBox.confirm('此操作将关闭窗口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        showDrawer.value = false
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
      
    }
    const cancel = () => {
      isOpenAddAppointment.value = false
      isMantle.value = false
    }
    
    return {
      loading,
      type,
      isShow,
      isUndeterminedShow,
      handleClick,
      handShow,
      weekDayList,
      dayList,
      weekDataList,
      isSearchList,

      searchDoctor,
      getDocTorList,
      reloadList,

      doctorList,
      statusBtnList,
      status,
      doctorID,

      startMonth,
      startDay,
      endMonth,
      endDay,
      start,
      end,

      isActive,
      handleClickDay,
      getDay,
      getWeeks,

      isShowDate,
      isPutAwayBtn,
      // 是否点击预约
      isOpenAddAppointment,
      // 蒙层
      isMantle,
      prevWeek,
      nextWeek,
      handleOpenEditAnApp,
      makeanappInfo,

      // 预约
      onBtnStatus,
      showDrawer,
      title,
      isADD,
      addAppointment,
      saveMakeAnAppointment,
      saveAndRegister,
      handlebtn,
      drawerClose,
      cancel,

      
      request,
    }
  }
})
</script>

<style lang="scss"  scoped>
.appointment-main {
  width: 100%;
  height: 100vh;
  background-color: #fff;
  display: flex;
  overflow: auto;

  .appointment-left {
    // width: 320px;
    flex: 0 0 320px;
    box-sizing: border-box;
    background: white;

    .opreation {
      width: 100%;
      height: 40px;
      line-height: 40px;
      display: flex;
      text-align: center;
      border-top: 1px solid $mainColor;
      border-bottom: 1px solid $mainColor;
      & > div {
        flex: 1;
      }
      & > div:nth-child(1) {
        border-right: 1px solid $mainColor;
      }
    }
  }
  .appoinment-right {
    // width: calc(100% - 300px);
    flex: 1;
    height: 100%;

    .appoinment-right-head {
      height: 40px;
      line-height: 40px;
      background: white;
      display: flex;
      font-weight: 600;
      font-size: $fontSize-2;

      .head-days {
        flex: 1;
        padding-left: 15px;
        color: $primaryText;
      }

      .days-switch {
        // flex: 1;
        text-align: right;
        padding-right: 15px;
        // width: 200px;
        display: flex;
        .add-btn {
          padding-left: 15px;
        }
      }
    }
  }

  .appoinment-operation {
    flex: 0 0 600px;
    height: 82%;
    background-color: #fff;
    box-shadow: 0 0 12px #e9e9e9, 0 0 12px #e9e9e9;

    .head-title {
      height: 40px;
      line-height: 40px;
      font-weight: bold;
      font-size: 20px;
      padding: 0 20px;
    }
  }
}


.isAvtive {
  background: $mainColor;
  color: white;
}

.plan-collapse {

  .plan-head {
    height: 40px;
    line-height: 40px;
    display: flex;
    cursor: pointer;
    & > span {
      padding-left: 15px;
      flex: 1;
    }
    .icon {
      padding-right: 15px;
    }
  }

  .plan-content {
    padding: 5px 15px;
    border-bottom: 1px solid $mainColor;

    .defult-btn {
      display: flex;
      justify-content: space-between;
    }

    .show-btn {
      display: flex;
      flex-wrap: wrap;
      .btn {
        margin: 5px;

        .btn-item {
          padding: 5px 10px;
          border: 1px solid $mainColor;
          color: $mainColor;
          border-radius: 4px;
          box-sizing: border-box;
          cursor: pointer
        }

        .btn-item-active {
          background-color: $mainColor;
          color: #fff;
        }
      }
    }
  }

  .content-scroll {
    height: 450px;
    overflow-y: scroll;
    background-color: #fff;
  }
}
</style>